<template>
  <main>
    <div class="userProfile">
      <div class="userProfileHeader">
        <img :src="data.avatar" alt="" class="avatar" />
        <div class="userInfo">
          <div class="userInfoHeader">
            <div class="name">{{ data.name }}</div>
            <el-tag type="success">{{ data.status }}</el-tag>
            <div style="margin-left: auto; display: flex; gap: 20px">
              <div class="func" v-if="!isMe" @click="send">私信</div>
              <!-- <div class="func" v-if="isMe" @click="editPasswordVisible = true">
                修改密码
              </div> -->
              <div class="func" v-if="isMe" @click="rechargeAccount">
                余额充值
              </div>
              <div class="func" v-if="isMe" @click="editVisible = true">
                修改资料
              </div>
              <div class="follow" v-if="!isMe" @click="followChange">
                <span v-if="!data.follow">+ 关注</span>
                <span v-else>取消关注</span>
              </div>
            </div>
          </div>
          <div class="info">
            <div class="statistics">文章数：{{ data.articleCount }}</div>
            <div class="statistics">粉丝数：{{ data.followCount }}</div>
            <div class="statistics">被点赞：{{ data.likeCount }}</div>
            <div class="statistics">关注数：{{ data.myFollowCount }}</div>
            <div class="statistics">注册时间：{{ data.createAt }}</div>
            <div class="statistics">余额：￥{{ data.balance }}</div>
          </div>
          <div class="bio">{{ data.bio || "这家伙很懒，没有留下备注~" }}</div>
        </div>
      </div>
      <Line />
      <div class="userProfileContent">
        <div class="tab">
          <div
            class="tab-item"
            :class="{ active: currentTab === item }"
            v-for="item in tabs"
            @click="currentTab = item"
          >
            {{ item }}
          </div>
        </div>
        <div>
          <List
            v-if="currentTab == '文章'"
            :user-id="userId"
            :status="isMe ? undefined : Enums.ARTICLE_ENUMS.已发布"
          />
          <UserListItem
            v-else
            v-for="user in userData"
            :key="user"
            :userId="user"
          />
        </div>
      </div>
    </div>
  </main>
  <el-dialog title="修改资料" v-model="editVisible">
    <el-form label-width="120px" :model="data" ref="formRef" :rules="rules">
      <el-form-item label="登录邮箱">
        <el-input v-model="data.email" disabled></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/api/upload"
          list-type="picture-card"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="data.avatar"
            :src="data.avatar"
            style="width: 100%; height: 100%"
            alt=""
          />
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="data.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="个人简介" prop="bio">
        <el-input
          v-model="data.bio"
          type="textarea"
          placeholder="请输入个人简介"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
  <el-dialog title="修改密码" v-model="editPasswordVisible">
    <el-form
      label-width="120px"
      :model="passwordForm"
      ref="passwordFormRef"
      :rules="passwordRule"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="passwordForm.oldPassword"
          placeholder="请输入旧密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          placeholder="请输入新密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input
          v-model="passwordForm.rePassword"
          placeholder="请输入确认密码"
          type="password"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editPasswordVisible = false">取 消</el-button>
      <el-button type="primary" @click="editPassword">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import Line from "@/components/Line.vue";
import { useRoute } from "vue-router";
import List from "../article/List.vue";
import UserListItem from "@/components/UserListItem.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/userStore";
import {
  followUser,
  getFollowingList,
  getUserProfile,
  unfollowUser,
} from "@/api/users";
import { recharge } from "@/api/users";
import { updateUserProfile } from "@/api/users";
import Enums from "@/utils/Enums";
import { sendMessage } from "@/api/message";
import router from "@/router";
const formRef = ref(null);
const editVisible = ref(false);
const editPasswordVisible = ref(false);
const route = useRoute();
let userId = route.params.id;
const currentTab = ref("文章"); // 当前选中的标签
// const tabs = ["文章"];
const tabs = ["文章", "关注"];
const passwordFormRef = ref(null);
const isMe = route.params.id == useUserStore().userInfo.id;
const editPassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("修改成功");
      editPasswordVisible.value = false;
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};

watch(
  () => route.params.id,
  (newVal) => {
    window.location.reload();
  }
);

const followChange = () => {
  if (data.value.follow) {
    unfollowUser({
      followerId: useUserStore().userInfo.id,
      followingId: data.value.id,
    });
  } else {
    followUser({
      followerId: useUserStore().userInfo.id,
      followingId: data.value.id,
    });
  }
  data.value.follow = !data.value.follow;
  ElMessage.success("操作成功");
};
const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  rePassword: "",
});
const passwordRule = {
  oldPassword: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  rePassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
    },
  ],
};
const userData = ref([]);
const data = ref({});
const rechargeAccount = () => {
  ElMessageBox.prompt("请输入充值金额", "余额充值", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[0-9]*$/,
    inputErrorMessage: "请输入数字",
  })
    .then(async ({ value }) => {
      await recharge({
        userId: useUserStore().userInfo.id,
        amount: value,
      });
      ElMessageBox.alert(`充值成功，充值金额：${value}`, "提示", {
        confirmButtonText: "确定",
      }).then(() => {
        getData();
      });
    })
    .catch(() => {});
};

const rules = {
  name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],

  avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
};
const submit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await updateUserProfile({
        avatar: data.value.avatar,
        bio: data.value.bio,
        userId: useUserStore().userInfo.id,
        username: data.value.name,
      });
      ElMessage.success("修改成功");
      useUserStore().userInfo = {
        ...useUserStore().userInfo,
        ...data.value,
      };
      // let userinfoData = JSON.parse(localStorage.getItem("user"));
      // localStorage.setItem(
      //   "user",
      //   JSON.stringify({
      //     ...userinfoData,
      //     user: {
      //       ...userinfoData.userInfo,
      //       ...data.value,
      //     },
      //   })
      // );

      window.location.reload();
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
const handleAvatarSuccess = (response, file) => {
  data.value.avatar = "http://localhost:8080/" + response.data;
  ElMessage.success("上传成功");
};
const getData = async () => {
  await getUserProfile({
    userId: userId,
    currentUserId: useUserStore().userInfo.id,
  }).then((res) => {
    data.value = res.data.data;
  });
  // 读取关注列表
  await getFollowingList({
    queryUserId: userId,
  }).then((res) => {
    userData.value = res.data.data;
  });
};
const send = async () => {
  await sendMessage({
    currentUserId: useUserStore().userInfo.id,
    targetUserId: Number(userId),
    content: "",
  });
  router.push("/notice/message");
};
getData();
</script>
<style scoped lang="less">
main {
  width: 70%;
  margin: 20px auto;
  background-color: #fff;
  padding: 30px;
  .userProfileHeader {
    display: flex;
    align-items: center;
    .userInfo {
      flex: 1;
      .userInfoHeader {
        display: flex;
        align-items: center;
      }
      .name {
        font-size: 24px;
        font-weight: bold;
        margin-right: 10px;
      }
      .bio {
        font-size: 16px;
        color: #969696;
        margin-top: 5px;
      }
    }
  }
  .info {
    display: flex;
    margin-top: 5px;
    gap: 14px;
    .statistics {
      padding-right: 14px;
      border-right: 1px solid #969696;
      &:last-child {
        border-right: none;
      }
    }
  }
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-right: 20px;
  }
}
.follow {
  margin-left: auto;
  cursor: pointer;
  color: #ec6149;
  padding: 5px 10px;
  border: 1px solid #ec6149;
  border-radius: 5px;
  user-select: none;
}
.func {
  .follow;
  background-color: #ec6149;
  color: #fff;
}
.userProfileContent {
  margin-top: 20px;
  .tab {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .tab-item {
      padding: 10px 20px;
      cursor: pointer;
      font-size: 18px;
      color: #969696;
      border-bottom: 2px solid #fff;
      transition: all 0.3s ease-in-out;
      &.active {
        color: #ec6149;
        border-bottom: 2px solid #ec6149;
      }
    }
  }
}
</style>
